package com.cogwheel.framework.graphics.ui;

import javax.media.opengl.GL2;
import com.cogwheel.framework.graphics.CSprite;
import com.cogwheel.framework.init.CPreferences;
import com.cogwheel.framework.util.CAssets;
import com.cogwheel.framework.util.CRectangle;
import com.cogwheel.framework.util.CUtils;
import com.cogwheel.framework.util.input.CKeyboard;
import com.cogwheel.framework.util.input.CMouse;

import static com.cogwheel.framework.util.input.CKeyboardState.*;

public class CTextBox extends CSprite{
	private CFont font;
	private String spriteID2;
	public boolean Active = false;
	
	public CTextBox(CPreferences preferences, String spriteID, String spriteID2, CFont font, CRectangle dimensions, int widthMultiplier) {
		super(preferences, spriteID, dimensions);
		this.font = font;
		this.font.Dimensions = new CRectangle((dimensions.x - dimensions.width / 2) + font.CWGGetText().length() / 2 * (this.font.Dimensions.width / this.font.CWGGetSymbolCount()) + 15, dimensions.y, dimensions.width * widthMultiplier, dimensions.height);
		this.spriteID2 = spriteID2;
	}
	
	public void CWGUpdate(CMouse mouse, CKeyboard keyboard){
		Active = this.Dimensions.Intersects(new CRectangle(mouse.CWGGetMouseCoords(), 1, 1));
		
		if (Active && (keyboard.CWGGetKeyboardState() == BUTTON_TYPED || keyboard.CWGGetKeyboardState() == BACK_TYPED)){
            if (keyboard.CWGGetKeyboardState() == BACK_TYPED && CWGGetText().length() >= 1){
                    keyboard.CSetState(NOTHING);
                    CWGSetText((String)CWGGetText().subSequence(0, CWGGetText().length() - 1));
                    return;
            }
            keyboard.CSetState(NOTHING);
            CWGSetText(CWGGetText() + keyboard.CGetKeyBuffer());
            keyboard.CClearKeyBuffer();
		}
	}
	
	public void CWGSetText(String text){ font.CWGSetText(text); }
	public String CWGGetText(){ return font.CWGGetText(); };
	
	@Override
	public void CBindTexture(GL2 gl){
		if (Active){
			if (spriteID2 != null && CUtils.CurrentTexture != spriteID2){
				CAssets.CWGGetTexture(spriteID2).enable(gl);
				CAssets.CWGGetTexture(spriteID2).bind(gl);
				
				CUtils.CurrentTexture = spriteID2;
			}
		}else{
			if (TextureID != null && CUtils.CurrentTexture != TextureID){
				CAssets.CWGGetTexture(TextureID).enable(gl);
				CAssets.CWGGetTexture(TextureID).bind(gl);
				
				CUtils.CurrentTexture = TextureID;
			}
		}
	}
	
	@Override
	public void CDraw(GL2 gl){
		gl.glLoadIdentity();
		CBindTexture(gl);
		CToOrtho();
		CDraw2D(gl);
		font.CDraw(gl);
	}
	
}
